<template>
	<view class="app-components-goods-layout-form-file-upload">
		<view class="app-components-goods-layout-form-file-upload__title e-flex e-flex-items-start">
			<view class="e-flex-1 e-flex e-flex-items-start ql-container">
				<text class="c-red e-p-r-8" v-if="info.hasRequired === 0">*</text>
				<text v-if="index">{{ index }}.</text>
				<view class="e-flex-1">
					<rich-text :nodes="info.title"></rich-text>
				</view>
			</view>
			<view class="e-p-l-20 text-nowra" v-if="totalPrice">
				<text class="c-red">
					{{ unitEn }}
					{{ priceFormat(totalPrice, 2) }}
				</text>
			</view>
		</view>
		<view class="app-components-goods-layout-form-file-upload__sub-title" v-if="info.illustrate">
			<rich-text :nodes="info.illustrate"></rich-text>
		</view>
		<view class="e-m-b-10" v-else></view>
		<FormItemImg :info="info" />
		<view class="">
			<view class="e-flex e-m-b-20" v-for="item in form?.fileList" :key="item.url">
				<view class="app-components-goods-layout-form-file-upload__input bg-white e-flex">
					<view class="e-m-r-20">
						<image class="img-32" src="/static/layoutForm/pdf.png" v-if="item.type === 'pdf'" />
						<image class="img-32" src="/static/layoutForm/docx.png" v-else-if="item.type === 'docx' || item.type === 'doc'" />
						<image class="img-32" src="/static/layoutForm/ppt.png" v-else-if="item.type === 'ppt' || item.type === 'pptx'" />
						<image class="img-32" src="/static/layoutForm/jpeg.png" v-else-if="item.type === 'jpeg'" />
						<image class="img-32" src="/static/layoutForm/jpg.png" v-else-if="item.type === 'jpg'" />
						<image class="img-32" src="/static/layoutForm/png.png" v-else-if="item.type === 'png'" />
						<image class="img-32" src="/static/layoutForm/xls.png" v-else-if="item.type === 'xls' || item.type === 'xlsx'" />
						<image class="img-32" src="/static/layoutForm/mp3.png" v-else-if="item.type === 'mp3'" />
						<image class="img-32" src="/static/layoutForm/mp4.png" v-else-if="item.type === 'mp4'" />
					</view>

					<view class="e-line-1 e-flex-1">
						<text class="c-secondary">{{ item.name }}</text>
					</view>
					<view class="e-m-l-30 cursor-pointer" @tap="handleDelFile(index)">
						<CloseOutlined class="c-secondary e-me-font-24 e-pc-font-12" />
					</view>
				</view>
			</view>
			<view class="e-flex" v-if="!formContext?.disabled && props.info.fileNum > (form?.fileList?.length || 0)">
				<view class="app-components-goods-layout-form-file-upload__input bg-white e-flex" @tap="handleSelectFile">
					<image src="/static/layoutForm/icon1.png" class="img-32 e-m-r-10" />
					<text class="c-secondary">{{ $t('layoutForm.addFile') }}</text>
				</view>
			</view>
		</view>

		<view class="app-components-goods-layout-form-file-upload__error e-flex" v-if="message">
			<image src="/static/layoutForm/error.png" class="img-40 e-m-r-22" />
			<text class="c-red">{{ message }}</text>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, toRef, inject, onMounted, onBeforeUnmount } from 'vue';
import type { GoodsFormFileUploadOption, LayoutFormModelValue } from '@/typings';
import FormItemImg from './formItemImg';
import { uploadFiles } from '@/common/request/api';
import { useCurrentInstance } from '@/common/hooks';
import { goodsLayoutFormContextKey } from '../tokens';
import type { GoodsLayoutFormItemContext } from '../tokens';
import { priceFormat, fileSizeToUnit, checkFileSize, selectFile, checkFileType, getFileType, type SelectFileAccept } from '@/common/utils';

const props = withDefaults(
	defineProps<{
		value: LayoutFormModelValue;
		index: number;
		info: GoodsFormFileUploadOption;
		unitEn: string;
	}>(),
	{}
);
const emit = defineEmits(['update:value']);
const ctx = useCurrentInstance();

const message = ref('');

const formContext = inject(goodsLayoutFormContextKey);

const form = computed({
	get() {
		return (
			props.value.find((item) => item.formOptionsId === props.info.id) || {
				formOptionsId: props.info.id,
				formOptionsInfoId: [],
				formOptionsInfoIdText: '',
				vle: '',
				vleid: '',
				fileList: []
			}
		);
	},
	set(v) {
		const list = [...props.value];
		const index = props.value.findIndex((item) => item.formOptionsId === props.info.id);
		if (index > -1) {
			list.splice(index, 1, v);
		} else {
			list.push(v);
		}
		emit('update:value', list);
	}
});

watch(
	() => form.value.vle,
	() => {
		message.value = '';
	}
);

const totalPrice = computed(() => (form.value.vle ? formContext?.getPrice?.(props.info) || 0 : 0));

const context: GoodsLayoutFormItemContext = reactive({
	info: toRef(props, 'info'),
	message,
	form,
	totalPrice
});

const accept = computed(() => {
	const fileType = props.info.fileType.split(',');
	return fileType.map((item) => item.toLowerCase());
});

const handleSelectFile = async () => {
	const fileRes = await selectFile({
		multiple: props.info.fileNum > 1,
		accept: accept.value as SelectFileAccept[]
	});
	const checkRes = await checkFileType(fileRes.tempFiles, accept.value as SelectFileAccept[]);
	if (checkRes) {
		ctx.$toastApp(ctx.$t('layoutForm.fileTypeError').replace('-TYPE-', `${props.info.fileType}`));
		return;
	}
	if (fileRes.tempFiles.length > props.info.fileNum) {
		ctx.$toastApp(ctx.$t('layoutForm.fileNumberError').replace('-NUMBER-', `${props.info.fileNum}`));
		return;
	}

	if (
		!fileRes.tempFiles.some((item) => {
			if (checkFileSize(item.size, props.info.fileSize)) {
				ctx.$toastApp(
					ctx
						.$t('layoutForm.fileSizeError')
						.replace('-NAME-', `${item.name}`)
						.replace('-NUMBER-', `${fileSizeToUnit(props.info.fileSize)}`)
				);
				return true;
			}
		})
	) {
		const res = await uploadFiles(fileRes.tempFiles);
		if (!form.value.fileList) {
			form.value.fileList = [];
		}
		res.forEach(async (item, index) => {
			const type = await getFileType(fileRes.tempFiles[index]);
			form.value.fileList!.push({
				name: item.data.name,
				url: item.data.url,
				type
			});
		});
	}
};

const handleDelFile = (index: number) => {
	form.value.fileList?.splice(index, 1);
};

onMounted(() => {
	formContext?.addField(context);
});
onBeforeUnmount(() => {
	formContext?.removeField(context);
});
</script>

<style lang="scss" scoped>
	@include appBem_b(components-goods-layout-form-file-upload) {
	    padding: 20rpx 30rpx 30rpx 30rpx;
	
	   @include appBem_e(title) {
	   	padding: 20rpx 0;
	   	font-size: 32rpx;
	   }
	
	    @include appBem_e(sub-title) {
	    	margin-bottom: 20rpx;
	    }
	
	    @include appBem_e(input) {
	        height: 72rpx;
	        border-radius: 2rpx;
	        border: 2rpx solid #E6E6E6;
	        padding: 0 10rpx 0 22rpx;

	    }
	
	
	    @include appBem_e(error) {
	    	margin-top: 10rpx;
	    	padding: 0 16rpx;
	    }
	}
</style>
